package com.mcxx.ansync.event;

import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Component
public class PropertiesEventHandler {
    @Autowired
    private ApplicationContext applicationContext;

    public static final Integer EVT_TYPE_CHANGE = 1;
    public static final Integer EVT_TYPE_ADD = 2;
    public static final Integer EVT_TYPE_DELETE = 3;


    public void publishChangeEvent(Object afterObj, String category, String desc) {
        publishChangeEvent(afterObj, EVT_TYPE_CHANGE, category, desc);
    }


    public void publishAddEvent(Object afterObj, String category, String desc) {
        publishChangeEvent(afterObj, EVT_TYPE_ADD, category, desc);
    }


    public void publishDeleteEvent(Object afterObj, String category, String desc) {
        publishChangeEvent(afterObj, EVT_TYPE_DELETE, category, desc);
    }

    private void publishChangeEvent(Object afterObj, Integer type, String category, String desc) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        UserAccountVo userAccountVo = WebUtil.getCurUserAccountVo(request);
        PropertiesChangeEvent event = new PropertiesChangeEvent(this, afterObj, type, category, desc, userAccountVo);
        applicationContext.publishEvent(event);
    }
}
